package com.yangcangclub.commons.velocity;

import com.yangcangclub.commons.exception.ApolloException;
import com.yangcangclub.commons.result.MessageEnum;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;


@Component
public class TemplateComponent {
    @Autowired
    protected VMEngine vmEngine;

    /**
     *
     * @param templateName  模板名称
     * @param paramMap  模板中参数集合
     * @return
     */
    public String templateMerge( String templateName,Map<String, Object> paramMap)  {
        try {
            Template tpl = this.vmEngine.getTemplate(TemplateProvider.PROVIDER_NAME, templateName);
            StringWriter sw = new StringWriter();
            VelocityContext ctx = new VelocityContext();
            Iterator<Map.Entry<String, Object>> paramIt = paramMap.entrySet().iterator();
            while (paramIt.hasNext()) {
                Map.Entry<String, Object> entry = paramIt.next();
                ctx.put(entry.getKey(), entry.getValue());
            }
            tpl.merge(ctx, sw);
            return sw.toString();
        } catch (Throwable e) {
            e.printStackTrace();
            throw new ApolloException(MessageEnum.TEMPLATE_ERROR);
        }
    }
}
